package wangwenjun.phase1.synchronizeddemo.caslock;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import util.ThreadUtil;

import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;

/**
 * @author ChangLiang
 * @date 2020/6/10
 */
@Slf4j
public class AppTest {

    private final CompareAndSetLock lock = new CompareAndSetLock();

    public void syncMethod() {
        try {
            lock.tryLock();
            ThreadUtil.sleepForSeconds(ThreadLocalRandom.current().nextInt(10));
        } catch (TryLockException e) {
            log.error(e.getMessage());
        } finally {
            lock.unlock();
        }
    }

    @Test
    @DisplayName("多个线程通过lock方法争抢锁")
    public void test() throws InterruptedException {
        AppTest lockTest = new AppTest();
        IntStream.range(0, 3).mapToObj(i -> new Thread(lockTest::syncMethod, "my-thread-" + i))
                .forEach(Thread::start);
        Thread.currentThread().join();
    }
}
